package com.sz.ruichar.manager.handler;

import java.util.Date;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.toolkit.StringUtils;
import com.sz.ruichar.builder.TextBuilder;
import com.sz.ruichar.entity.beans.TUserScore;
import com.sz.ruichar.entity.beans.WeixinUser;
import com.sz.ruichar.entity.model.constant.Constant;
import com.sz.ruichar.service.mapper.beans.WeixinUserMapper;
import com.sz.ruichar.service.wechat.WeixinService;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

/**
 * 
 * @author Binary Wang
 *
 */
@Component
public class SubscribeHandler extends AbstractHandler 
{
	@Resource
	private WeixinUserMapper weiXinUserMapper;
	@Transactional
	@Override
	public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService,
			WxSessionManager sessionManager) throws WxErrorException 
	{

		this.logger.info("新关注用户 OPENID: " + wxMessage.getFromUser());

		WeixinService weixinService = (WeixinService) wxMpService;

	    // 获取微信用户基本信息
	    WxMpUser userWxInfo = weixinService.getUserService().userInfo(wxMessage.getFromUser(), null);
	
	    if (userWxInfo != null) 
	    {
	    	String openId = userWxInfo.getOpenId();
	    	WeixinUser param = new WeixinUser();
	    	param.setOpenid(openId);
	    	WeixinUser userData = weiXinUserMapper.getRecordsByCondition(param);
	    	if(userData!=null && StringUtils.isNotEmpty(userData.getOpenid()))
	    	{
	    		//更新用户信息
	    		WeixinUser wxUser = new WeixinUser();
		    	wxUser.setOpenid(openId);
		    	wxUser.setCity(userWxInfo.getCity());
		    	wxUser.setCountry(userWxInfo.getCountry());
		    	wxUser.setNickName(userWxInfo.getNickname());
		    	wxUser.setPicUrl(userWxInfo.getHeadImgUrl());
		    	wxUser.setProvince(userWxInfo.getProvince());
		    	wxUser.setSex(userWxInfo.getSex());
		    	wxUser.setId(userData.getId());
		    	wxUser.setTsp(new Date());
		    	wxUser.updateById();
	    	}
	    	else
	    	{
	    		//插入用户
	    		WeixinUser wxUser = new WeixinUser();
		    	wxUser.setOpenid(openId);
		    	wxUser.setCity(userWxInfo.getCity());
		    	wxUser.setCountry(userWxInfo.getCountry());
		    	wxUser.setNickName(userWxInfo.getNickname());
		    	wxUser.setPicUrl(userWxInfo.getHeadImgUrl());
		    	wxUser.setProvince(userWxInfo.getProvince());
		    	wxUser.setSex(userWxInfo.getSex());
		    	wxUser.setTsp(new Date());
		    	weiXinUserMapper.insert(wxUser);
		    	//初始化积分
		    	TUserScore score = new TUserScore();
		    	score.setOpenid(openId);
		    	score.setScore(Constant.initScore);
				score.insert();

	    	}
	    	
	    	
//	    	CmhWechatUser user = new CmhWechatUser();
//	    	user.setHeadPic(userWxInfo.getHeadImgUrl());
//	    	user.setIsSubscribe(Constant.YES);
//	    	user.setNickName(userWxInfo.getNickname());
//	    	user.setOpenId(userWxInfo.getOpenId());
//	    	user.setCity(userWxInfo.getCity());
//	    	user.setProvince(userWxInfo.getProvince());
//	    	user.setCountry(userWxInfo.getCountry());
//	    	user.setGroupId(userWxInfo.getGroupId());
//	    	user.setLanguage(userWxInfo.getLanguage());
//	    	user.setRemark(userWxInfo.getRemark());
//	    	user.setSex(userWxInfo.getSex());
//	    	user.setSubscribeTime(this.getSubscribeDate(userWxInfo.getSubscribeTime()));
//	    	user.setUnionId(userWxInfo.getUnionId());
//	    	user.setPhone("");
//	    	user.setTsp(new Date());
//	    	wechatUserMapper.insert(user);
	    }
	
	    WxMpXmlOutMessage responseResult = null;
	    try {
	      responseResult = handleSpecial(wxMessage);
	    } catch (Exception e) {
	      this.logger.error(e.getMessage(), e);
	    }
	
	    if (responseResult != null) {
	      return responseResult;
	    }
	
	    try {
	      return new TextBuilder().build("感谢关注", wxMessage, weixinService);
	    } catch (Exception e) {
	      this.logger.error(e.getMessage(), e);
	    }
	
	    return null;
  }

  /**
   * 处理特殊请求，比如如果是扫码进来的，可以做相应处理
   */
  protected WxMpXmlOutMessage handleSpecial(WxMpXmlMessage wxMessage) throws Exception 
  {
    //TODO
    return null;
  }
  
  private Date getSubscribeDate(Long timesatmp)
  {
	  Date d = new Date();
	  try
	  {
		  d = new Date(timesatmp);
	  }
	  catch(Exception e)
	  {
		  
	  }
	  return d;
  }

}
